import React, { useContext, useEffect, useState } from 'react';
import styles from './style/index.module.less';
import {
  Breadcrumb,
  Button,
  Form,
  Grid,
  Message,
  Modal,
  Space,
  Spin,
} from '@arco-design/web-react';
import cs from 'classnames';
import { GlobalContext } from '@/context';
import useLocale from '@/utils/useLocale';
import locale from './locale';
import { personal } from './personal';
import { ReqViolationCreate } from '@/api/interface/violation';
import { MONTHS, volation } from './violation';
import { Who } from './who';
import Supporting from './supporting';
import Signed from './signed';
import { Search, entityGet } from '@/api/modules/entity';
import { Emirates, Enums } from '@/api/modules';
import { EnumsRes } from '@/api/interface';
import { CreateFrom } from '@/api/modules/violation';
import { useHistory } from 'react-router-dom';
import useIsMountedRef from '@/utils//useIsMountedRef';
import Violation from '@/assets/Violation.svg';
import Preview from './preview';
import CustomConfirmMadel from '@/components/CustomConfirmMadel';

// import { Prompt } from 'react-router';
const { useForm } = Form;
const { Row, Col } = Grid;
function Create() {
  const [loading, setLoading] = useState(false);
  const { rtl, lang } = useContext(GlobalContext);
  const t = useLocale(locale);
  const [form] = useForm();

  const defaultObj = {
    complainantRole: null,
    eid: '',
    email: '',
    emirate: '',
    emirateEntity: '',
    emirateEntityOther: '',
    fullName: '',
    hasReported: false,
    mobile: '',
    nationality: null,
    refEntity: '',
    refMonth: '',
    refRefNumber: '',
    refYear: '',
    signedDocHref: [],
    source: null,
    sourceOther: '',
    supportEntities: [],
    violationAdditionalDetails: '',
    violationDate: '',
    violationDesc: '',
    violationType: '',
    violators: [],
    unifiedNumber: '',
  };

  const [formData, setFormDta] = useState<ReqViolationCreate>(defaultObj);

  const onchange = (values) => {
    setFormDta((e) => ({ ...e, ...values }));
  };

  const onValuesChange = (
    _: unknown,
    values: React.SetStateAction<ReqViolationCreate>
  ) => {
    onchange(values);
  };

  // 获取枚举数据

  const [entitys, setEntitys] = useState([]);
  const getEntitys = (e) => {
    setEntitys([]);
    form.setFieldsValue({
      emirateEntity: undefined,
      emirateEntityOther: '',
    });
    entityGet({ emirate: e, active: true })
      .then((res) => {
        const Other = {
          id: -1,
          name: 'Other - Authority',
          nameAr: 'سلطات اتحادية أخرى',
        };
        setEntitys(() => [...res.data, Other]);
      })
      .catch((e) => {
        console.log(e);
      });
  };

  const [enums, setEnums] = useState<{ [key: string]: EnumsRes[] }>({
    emirateEnums: [],
    complainantEnums: [],
    nationalityEnums: [],
    sourceEnums: [],
    violationTypeEnums: [],
    violatorOrWitnessEnums: [],
  });
  const getEnums = async () => {
    try {
      const enumData = await Promise.all([
        Enums({ type: 'EmirateEnums' }),
        // Emirates(),
        Enums({ type: 'ComplainantEnums' }),
        Enums({ type: 'NationalityEnums' }),
        Enums({ type: 'SourceEnums' }),
        Enums({ type: 'ViolationTypeEnums' }),
        Enums({ type: 'ViolatorOrWitnessEnums' }),
      ]);
      if (isMountedRef.current) {
        setEnums({
          emirateEnums: enumData[0].data,
          complainantEnums: enumData[1].data,
          nationalityEnums: enumData[2].data,
          sourceEnums: enumData[3].data.filter(
            (a) => a.key !== 'ENT' && a.key !== 'COMP'
          ),
          violationTypeEnums: enumData[4].data,
          violatorOrWitnessEnums: enumData[5].data,
        });
      }
    } catch (e) {}
  };
  const isMountedRef = useIsMountedRef();
  useEffect(() => {
    getEnums();
    form.setFieldsValue({
      hasReported: false,
    });
  }, []);

  const history = useHistory();

  const onCreate = () => {
    form.validate((errors) => {
      if (!errors) {
        // if (formData.signedDocHref.length <= 0) {
        //   Message.warning(t['signedDocHref.empty']);
        //   return;
        // }
        // formData.source =
        //   formData.source === 'OTHER' ? '' : formData.source ;
        // formData.sourceOther =
        //   formData.source === 'OTHER' ? formData.sourceOther : '';
        formData.emirateEntityOther =
          formData.emirateEntity === -1 ? formData.emirateEntityOther : '';
        formData.eid = formData.eid.replace(/-/g, '');

        setLoading(true);
        CreateFrom(formData)
          .then(() => {
            setLoading(false);

            setIsBlocked(false);
            Message.success(t['create.success']);
            history.goBack();
          })
          .catch(() => {
            setLoading(false);
          });
      }
    });
  };

  const toPath = (path) => {
    history.replace({
      pathname: path,
    });
  };
  const [previewVisible, setPreviewVisible] = useState<boolean>(false);

  const [months, setMonths] = useState<string[]>(MONTHS);

  function isDefault(obj) {
    for (const [key, value] of Object.entries(obj)) {
      if (Array.isArray(value)) {
        if (value.length !== 0) {
          return false;
        }
      } else if (typeof value === 'object' && value !== null) {
        if (!isDefault(value)) {
          return false;
        }
      } else if (value !== defaultObj[key]) {
        return false;
      }
    }
    return true;
  }
  const [isBlocked, setIsBlocked] = useState(false);
  useEffect(() => {
    const is = !isDefault(formData);
    if (is) {
      setIsBlocked(is);
    }
  }, [formData]);

  return (
    <>
      <CustomConfirmMadel when={isBlocked} />

      <Spin loading={loading} className={cs(styles['spin'], rtl ? 'rtl' : '')}>
        <div className={cs(styles['layout-breadcrumb'], rtl ? 'rtl' : '')}>
          <Breadcrumb>
            <Breadcrumb.Item
              onClick={() => toPath('/Violation/List')}
              className={'cursor-pointer '}
            >
              <Violation
                style={{
                  [rtl ? 'marginLeft' : 'marginRight']: '8px',
                }}
                className={cs(
                  rtl ? styles['rtl-icon'] : styles.icon,
                  'arco-icon'
                )}
              />
              {t['menu.violation']}
            </Breadcrumb.Item>
            <Breadcrumb.Item>{t['menu.violation.create']}</Breadcrumb.Item>
          </Breadcrumb>
        </div>
        <div>
          <Form
            autoComplete="off"
            form={form}
            labelAlign="left"
            labelCol={{ span: 5 }}
            wrapperCol={{ span: 19 }}
            // initialValues={formData}
            onValuesChange={onValuesChange}
            layout="vertical"
            validateMessages={{
              required: () => t['empty'],
            }}
            validateTrigger={['onBlur', 'onChange']}
          >
            {personal(
              formData,
              rtl,
              t,
              lang,
              enums.nationalityEnums,
              enums.sourceEnums,
              enums.complainantEnums
            )}
            <div className={styles['space']}></div>
            {volation(
              formData,
              form,
              rtl,
              t,
              lang,
              enums.emirateEnums,
              enums.violationTypeEnums,
              entitys,
              getEntitys,
              months,
              setMonths
            )}
          </Form>
          <div className={styles['space']}></div>

          <Who
            complainantEnums={enums.violatorOrWitnessEnums}
            nationalityEnums={enums.nationalityEnums}
            value={formData.violators}
            onPush={(e) => {
              onchange({ violators: e });
            }}
          />
          <div className={styles['space']}></div>
          <Supporting
            value={formData.supportEntities}
            onPush={(e) => {
              onchange({ supportEntities: e });
            }}
          />
          <div className={styles['space']}></div>
          <Signed
            value={formData.signedDocHref}
            onPush={(e) => {
              onchange({ signedDocHref: e });
            }}
          />
          <div className={styles['space']}></div>
          <Row justify="end" style={{ paddingBottom: '20px' }}>
            <Space size={20}>
              <Button
                type="outline"
                size="large"
                onClick={() => setPreviewVisible(true)}
              >
                {t['preview']}
              </Button>
              <Button
                className={styles['button']}
                type="primary"
                size="large"
                onClick={onCreate}
              >
                {t['create']}
              </Button>
            </Space>
          </Row>
        </div>

        <Preview
          enums={enums}
          formData={formData}
          visible={previewVisible}
          entitys={entitys}
          onVisible={(e) => {
            setPreviewVisible(e);
          }}
        />
      </Spin>
    </>
  );
}

export default Create;
